摘要|Using Apollo with TypeScript 发表于 2018-03-16 | 更新于: 2019-04-28 | 分类于 技术备忘 | 阅读次数: 字数统计: 330 | 阅读时长 ≈ 2 typescript 需要额外定义类型12345678910111213141516171819202122232425262728293031323334353637383940import React from "react";import gql from "graphql-tag";import { graphql } from "react-apollo";const HERO_QUERY = gql` query GetCharacter($episode: Episode!) { hero(episode: $episode) { name id friends { name id appearsIn } } }`;//类型type Hero = { name: string; id: string; appearsIn: string[]; friends: Hero[];};//查询结果的类型type Response = { hero: Hero;};const withCharacter = graphql<Response>(HERO_QUERY, { options: () => ({ variables: { episode: "JEDI" } })});export default withCharacter(({ data: { loading, hero, error } }) => { if (loading) return <div>Loading</div>; if (error) return <h1>ERROR</h1>; return ...// actual component with data;}); 对于查询参数也需要定义类型123456789type InputProps = { episode: string};const withCharacter = graphql<Response, InputProps>(HERO_QUERY, { options: ({ episode }) => ({ variables: { episode } }),}); 在包装组件获取 props 时也需要定义1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import React from "react";import gql from "graphql-tag";import { graphql, NamedProps, QueryProps} from "react-apollo";const HERO_QUERY = gql` query GetCharacter($episode: Episode!) { hero(episode: $episode) { name id friends { name id appearsIn } } }`;type Hero = { name: string; id: string; appearsIn: string[]; friends: Hero[];};type Response = { hero: Hero;};type WrappedProps = Response & QueryProps;type InputProps = { episode: string};const withCharacter = graphql<Response, InputProps, WrappedProps>(HERO_QUERY, { options: ({ episode }) => ({ variables: { episode } }), props: ({ data }) => ({ ...data })});export default withCharacter(({ loading, hero, error }) => { if (loading) return <div>Loading</div>; if (error) return <h1>ERROR</h1>; return ...// actual component with data;}); 使用class组件定义